package cn.work.control;

import cn.work.bean.serviceclassbean;
import cn.work.dao.serviceclassDao;
import com.google.gson.Gson;

import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.*;
import java.io.IOException;
import java.util.List;

@WebServlet(name = "ServiceClassListServlet", value = "/ServiceClassListServlet")
public class ServiceClassListServlet extends HttpServlet {
    private serviceclassDao dao = new serviceclassDao();

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("UTF-8");
        // 获取所有分类数据
        List<serviceclassbean> categories = dao.getAllCategories();

        System.out.println("333获取的分类数据：");
        for (serviceclassbean category : categories) {
            System.out.println("ID: " + category.getServiceclass_id() + ", Name: " + category.getServiceclass_name());
        }
        // 设置响应的内容类型为 JSON
        response.setContentType("application/json;charset=UTF-8");

        // 使用 Gson 将分类数据转换为 JSON 格式
        Gson gson = new Gson();
        String jsonResponse = gson.toJson(categories);

        // 将 JSON 数据写入响应
        System.out.println("返回的JSON数据: " + jsonResponse); // 打印响应数据，调试用
        response.getWriter().write(jsonResponse);
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doGet(request, response); // 复用 GET 请求处理
    }
}
